<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节流</title>
</head>
<style>
    body {
        height: 5000px;
    }
</style>
<body>
    <script>

        /*
        * 节流函数
        * handler： 参入函数，wait: 频率时间
        */

        function myTrottle(handler, wait) {
            if (typeof handler !== 'function') throw new Error('handler must be a function')
            if (typeof wait === 'undefined') wait = 400

            let previous = 0, timer = null

            return function proxy(...args) {
                let now = new Date(),
                    interval = wait - (now - previous),
                    self = this
                console.log(interval)
                if (interval <= 0) {
                    clearTimeout(timer) // 知识将系统中的定时器清楚了，但是timer还在
                    timer = null
                    // 此时已经超过频率值，可以执行
                    handler.call(self, ...args)
                    previous = new Date()
                } else if (!timer) {
                    // 还在频率范围内，不执行handler
                    // 可以定时器监听 如果到了时间，自动开始执行
                    timer = setTimeout(()=> {
                        clearTimeout(timer) // 知识将系统中的定时器清楚了，但是timer还在
                        timer = null
                        handler.call(self, ...args)
                        previous = new Date()
                    },interval)
                }
            }
        }

        function scrollFn() {
            console.log('滚动了')
        }
        window.onscroll = myTrottle(scrollFn, 1000)
    </script>
</body>
</html>

